package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.DataBaseHelper;
import com.ruoyi.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.redis.CacheUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.SysCompanyBo;
import com.ruoyi.system.domain.vo.SysCompanyVo;
import com.ruoyi.system.domain.SysCompany;
import com.ruoyi.system.mapper.SysCompanyMapper;
import com.ruoyi.system.service.ISysCompanyService;

import java.util.*;

/**
 * 公司部门管理Service业务层处理
 *
 * @author zyb
 * @date 2024-12-03
 */
@RequiredArgsConstructor
@Service
public class SysCompanyServiceImpl implements ISysCompanyService {

    private final SysCompanyMapper baseMapper;

    /**
     * 查询公司部门管理
     */
    @Override
    public SysCompanyVo queryById(Long companyId){
        return baseMapper.selectVoById(companyId);
    }


    /**
     * 查询公司部门管理列表
     */
    @Override
    public List<SysCompanyVo> queryList(SysCompanyBo bo) {
        LambdaQueryWrapper<SysCompany> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysCompany> buildQueryWrapper(SysCompanyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysCompany> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), SysCompany::getCompanyName, bo.getCompanyName())
            .orderByAsc(SysCompany::getParentId)
            .orderByAsc(SysCompany::getOrderNum);
        return lqw;
    }

    /**
     * 新增公司部门管理
     */
    @Override
    public Boolean insertByBo(SysCompanyBo bo) {
        SysCompany add = BeanUtil.toBean(bo, SysCompany.class);
        validEntityBeforeSave(add);
        SysCompany info = baseMapper.selectById(bo.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("公司停用，不允许新增");
        }
        add.setAncestors(info.getAncestors() + StringUtils.SEPARATOR + add.getParentId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCompanyId(add.getCompanyId());
        }
        return flag;
    }

    /**
     * 修改公司部门管理
     */
    @Override
    public Boolean updateByBo(SysCompanyBo bo) {
        SysCompany update = BeanUtil.toBean(bo, SysCompany.class);
        validEntityBeforeSave(update);
        SysCompany newParentDept = baseMapper.selectById(update.getParentId());
        SysCompany oldDept = baseMapper.selectById(update.getCompanyId());
        if (ObjectUtil.isNotNull(newParentDept) && ObjectUtil.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + StringUtils.SEPARATOR + newParentDept.getCompanyId();
            String oldAncestors = oldDept.getAncestors();
            update.setAncestors(newAncestors);
            updateDeptChildren(update.getCompanyId(), newAncestors, oldAncestors);
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (UserConstants.DEPT_NORMAL.equals(update.getStatus()) && StringUtils.isNotEmpty(update.getAncestors())
            && !StringUtils.equals(UserConstants.DEPT_NORMAL, update.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(update);
        }
        return flag;
    }

    /**
     * 修改子元素关系
     *
     * @param companyId    被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long companyId, String newAncestors, String oldAncestors) {
        List<SysCompany> children = baseMapper.selectList(new LambdaQueryWrapper<SysCompany>()
            .apply(DataBaseHelper.findInSet(companyId, "ancestors")));
        List<SysCompany> list = new ArrayList<>();
        for (SysCompany child : children) {
            SysCompany company = new SysCompany();
            company.setCompanyId(child.getCompanyId());
            company.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(company);
        }
        if (CollUtil.isNotEmpty(list)) {
            baseMapper.updateBatchById(list);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param update 当前公司
     */
    private void updateParentDeptStatusNormal(SysCompany update) {
        String ancestors = update.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        baseMapper.update(null, new LambdaUpdateWrapper<SysCompany>()
            .set(SysCompany::getStatus, UserConstants.DEPT_NORMAL)
            .in(SysCompany::getCompanyId, Arrays.asList(deptIds)));
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysCompany entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除公司部门管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
